import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.js'
import cache from '@/utils/cache'
class XCRequest {
  private instance: AxiosInstance
  private loading?: LoadingInstance
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.instance.interceptors.request.use(
      (config) => {
        const token = cache.getCache('cms-token')
        if (token) {
          config!.headers!.Authorization = `Bearer ${token}`
        }
        //添加加载动画
        this.loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        //关闭加载动画
        this.loading?.close()
        // 拦截响应的数据
        return res.data
      },
      (err) => {
        this.loading?.close()
        return err
      }
    )
  }
  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  get<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'get' })
  }
  post<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'post' })
  }
  delete<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'delete' })
  }
  patch<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'patch' })
  }
}
export default XCRequest
